<?php

class GuestbookController extends Zend_Controller_Action {

	public function indexAction () {
		$guestbook = new Application_Model_GuestbookMapper();
		$this->view->entries = $guestbook->fetchAll();
	}

	public function addAction () {
		$request = $this->getRequest();
		$form = new Application_Form_Guestbook();
		
		if ( $this->getRequest()->isPost() ) {
			if ( $form->isValid( $request->getPost() ) ) {
				$data = new Application_Model_Guestbook( $form->getValues() );
				$mapper = new Application_Model_GuestbookMapper();
				$mapper->save( $data );
				return $this->_helper->redirector( 'index' );
			}
		}
		
		$this->view->form = $form;
	}

	public function editAction () {
		$request = $this->getRequest();
		$form = new Application_Form_Guestbook();
		
		if ( $this->getRequest()->isPost() ) {
			if ( $form->isValid( $request->getPost() ) ) {
				$data = new Application_Model_Guestbook( $form->getValues() );
				$mapper = new Application_Model_GuestbookMapper();
				$mapper->save( $data );
				return $this->_helper->redirector( 'index' );
			}
		} else {
			if ( $request->getParam( 'id' ) ) {
				$guestbookMapper = new Application_Model_GuestbookMapper();
				$guestbook = new Application_Model_Guestbook();
				$guestbookMapper->find( $request->getParam( 'id' ), $guestbook );
				
				$values = array( 
					'comment' => $guestbook->comment, 'created' => $guestbook->created, 'email' => $guestbook->email, 'id' => $request->getParam( 'id' ) 
				);
				$form->populate( $values );
			} else {
				return $this->_helper->redirector( 'index' );
			}
		}
		
		$this->view->form = $form;
	}

	public function viewAction () {
		$request = $this->getRequest();
		if ( $request->getParam( 'id' ) ) {
			$guestbookMapper = new Application_Model_GuestbookMapper();
			$guestbook = new Application_Model_Guestbook();
			$guestbookMapper->find( $request->getParam( 'id' ), $guestbook );
			
			$this->view->email 		= $guestbook->email;
			$this->view->comment 	= $guestbook->comment;
			$this->view->created 	= $guestbook->created;
		} else {
			return $this->_helper->redirector( 'index' );
		}
	}

}